<template>
  <div class="about-master-container">
    <base-breadcrumb :breadcrumb="!isAudit">
      <a-form-model
        ref="RuleForm"
        :model="formData"
        :rules="rules"
      >
        <a-card
          v-loading="loading"
          :bordered="false"
        >
          <title-name title="基本信息" />
          <a-row>
            <a-col span="8">
              <a-form-model-item label="日志编号">
                <BaseInput
                  v-model="formData.code"
                  disabled
                />
              </a-form-model-item>
            </a-col>
            <!-- <a-col span="8">
              <a-form-model-item
                label="所属分公司"
                prop="branchComId"
              >
                <SelectSubCompany
                  ref="selectSubCompany"
                  v-model="formData.branchComId"
                  :disabled="state == 3"
                  placeholder="请选择"
                  @change="getBranchComId"
                />
              </a-form-model-item>
            </a-col>
            <a-col :span="8">
              <a-form-model-item
                label="项目名称"
                prop="projectId"
              >
                <SelectProject
                  ref="selectProject"
                  v-model="formData.projectId"
                  placeholder="请选择"
                  :form="formData"
                  :is-clear="id == ''"
                  :disabled="state == 3"
                  key-value="branchComId"
                  @change="getProId"
                />
              </a-form-model-item>
            </a-col> -->
            <a-col :span="16">
              <a-form-model-item
                label="所属单位"
                prop="projectId"
              >
                <OrgTreeSelect
                  v-model="formData.projectId"
                  :disabled="state == 3"
                  is-auto-select-first
                  @select="setProject"
                />
              </a-form-model-item>
            </a-col>
            <a-col span="8">
              <a-form-model-item label="项目经理">
                <BaseInput
                  v-model="formData.projectManager"
                  disabled
                />
              </a-form-model-item>
            </a-col>
            <a-col :span="8">
              <a-form-model-item
                label="维保单编号"
                prop="maintenanceCode"
              >
                <a-select
                  v-model="formData.maintenanceCode"
                  placeholder="请选择"
                  :disabled="state == 3"
                  @focus="getInfo"
                >
                  <a-select-option
                    v-for="item in Codedata"
                    :key="item.id"
                    :value="item.id"
                  >
                    {{
                      item.id
                    }}
                  </a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>

            <a-col span="8">
              <a-form-model-item label="维保方案编号">
                <BaseInput
                  v-model="formData.planCode"
                  disabled
                />
              </a-form-model-item>
            </a-col>
            <a-col span="8">
              <a-form-model-item label="日志日期">
                <BaseInput
                  v-model="formData.createTime"
                  disabled
                />
              </a-form-model-item>
            </a-col>
          </a-row>
        </a-card>
        <a-card
          v-loading="loading"
          :bordered="false"
        >
          <title-name title="基本情况" />
          <a-row>
            <a-col :span="24">
              <a-form-model-item
                label="出勤人数（各工种各多少人）"
                prop="attendanceNum"
              >
                <BaseTextarea
                  v-model="formData.attendanceNum"
                  :max-length="2000"
                  :disabled="state == 3"
                  placeholder="请输入"
                />
              </a-form-model-item>
            </a-col>
            <a-col :span="8">
              <a-form-model-item
                label="总人数"
                prop="totalNum"
              >
                <BaseInputNumber
                  v-model="formData.totalNum"
                  placeholder="请输入"
                  :max-length="100"
                  :min="0"
                  :is-int="true"
                  :disabled="state == 3"
                />
              </a-form-model-item>
            </a-col>
            <a-col :span="24">
              <a-form-model-item
                label="机械、设备使用情况（主要机械情况）"
                prop="equipmentInfo"
              >
                <BaseTextarea
                  v-model="formData.equipmentInfo"
                  :max-length="2000"
                  :disabled="state == 3"
                  placeholder="请输入"
                />
              </a-form-model-item>
            </a-col>
          </a-row>
        </a-card>
        <a-card
          v-loading="loading"
          :bordered="false"
        >
          <title-name title="工作内容" />
          <a-row>
            <a-col :span="24">
              <a-form-model-item
                label="当天施工内容实际完成情况及主要工程量"
                prop="constructionInfo"
              >
                <BaseTextarea
                  v-model="formData.constructionInfo"
                  :max-length="2000"
                  :disabled="state == 3"
                  placeholder="请输入"
                />
              </a-form-model-item>
            </a-col>
            <a-col :span="24">
              <a-form-model-item
                label="使用的主要材料规格、数量（日消耗量）"
                prop="materialInfo"
              >
                <BaseTextarea
                  v-model="formData.materialInfo"
                  :max-length="2000"
                  :disabled="state == 3"
                  placeholder="请输入"
                />
              </a-form-model-item>
            </a-col>
            <a-col :span="24">
              <a-form-model-item
                label="施工现场有关会议内容（主要简要概述）"
                prop="meetingInfo"
              >
                <BaseTextarea
                  v-model="formData.meetingInfo"
                  :max-length="2000"
                  :disabled="state == 3"
                  placeholder="请输入"
                />
              </a-form-model-item>
            </a-col>
            <a-col :span="24">
              <a-form-model-item
                label="试块制作情况"
                prop="makeInfo"
              >
                <BaseTextarea
                  v-model="formData.makeInfo"
                  :max-length="2000"
                  :disabled="state == 3"
                  placeholder="请输入"
                />
              </a-form-model-item>
            </a-col>
            <a-col :span="24">
              <a-form-model-item
                label="材料进场、送检情况及当日取回试验报告编号及结果"
                prop="resultInfo"
              >
                <BaseTextarea
                  v-model="formData.resultInfo"
                  :max-length="2000"
                  :disabled="state == 3"
                  placeholder="请输入"
                />
              </a-form-model-item>
            </a-col>
          </a-row>
        </a-card>

        <a-card
          v-loading="loading"
          :bordered="false"
        >
          <title-name title="相关附件" />
          <UploadTableNew
            ref="uploadTable"
            :mode="mode"
            :disabled="state == 3"
            :init-file-list="formData.fileList"
            :need-page="false"
            :business-code="'CUSTOMER03'"
            :use-multi-delete="true"
            :use-multi-export="true"
          />
        </a-card>
      </a-form-model>

      <div class="pub-header-btn page-btn-right-top">
        <a-button
          v-if="state != 3"
          :loading="loading"
          type="primary"
          @click="onSave"
        >
          保存草稿
        </a-button>
        <a-button
          v-if="state != 3"
          :loading="loading"
          type="primary"
          @click="submit"
        >
          提交
        </a-button>
        <a-button
          v-checkVisibleInDetail
          @click="$close"
        >
          关闭
        </a-button>
      </div>
    </base-breadcrumb>

    <a-modal
      v-if="infoShow"
      title="维保单编号选择"
      :visible="infoShow"
      @ok="getPlanId"
      @cancel="closeInfo"
    >
      <searchData
        :search-data="searchArr"
        @search="search"
      />
      <b-table
        ref="modalTable"
        :scroll="{ y: 300 }"
        :loading="tableLoading"
        :request="loadData"
        :select-config="{ use: true, type: 'radio', rowKey: 'id' }"
        :page-keys="['pageNo', 'pageSize', 'total']"
        :columns="infoColumns"
        @row-click="(e, row) => (this.selectRow = row)"
      />
      <template slot="footer">
        <a-button @click="closeInfo">
          取消
        </a-button>
        <a-button
          type="primary"
          :loading="modelLoad"
          @click="getPlanId"
        >
          提交
        </a-button>
      </template>
    </a-modal>
  </div>
</template>

<script>
import { planAddFile, planFileList, planFileListDel, planListDetail, print } from '@/api/material/procurement/plan'
import { getMaintenanceInfo } from '@/api/complaint/maintenance'
import { getCustomerMaintenanceLogById, insertSelective, updateByPrimaryKeySelective, getPlanCode, getProjectInfo, submitMaintenanceLog } from '@/api/complaint/maintenancelog'
import { getComplaintList } from '@/api/complaint/maintenance'
import SelectSubCompany from '@/components/Select/SelectSubCompany' // 分公司
import SelectProject from '@/components/Select/SelectProject' // 项目名称

export default {
  name: 'a' + Date.now(),
  props: {
    isAudit: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      id: '',
      modelLoad: false,
      tableLoading: false,
      handData: {},
      Codedata: [],
      searchArr: [
        {
          name: '维保单编号/发起人',
          value: 'logQuery',
          type: 'input'
        },
        {
          name: '维保事项',
          value: 'infoId',
          type: 'select',
          data: []
        }
      ],
      infoColumns: [
        {
          title: '维保单编号',
          dataIndex: 'code'
        },
        {
          title: '维保发起人',
          dataIndex: 'createUser'
        },
        {
          title: '维保事项',
          dataIndex: 'infoName'
        },
        {
          title: '维保诉求',
          dataIndex: 'reason'
        },
        {
          title: '维保发起时间',
          dataIndex: 'createTime'
        }
      ],
      infoShow: false,
      infoQueryParam: {
        status: 1
      },
      key: '1',
      loading: false,
      state: Number(this.$route.query.state),
      isSubmit: false,
      statuCode: '3',
      selectRow: [],
      row: this.$route.query.row,
      formData: {
        projectId: '',
        branchComId: '',
        equipmentInfo: '',
        attendanceNum: '',
        constructionInfo: '',
        materialInfo: '',
        makeInfo: '',
        resultInfo: '',
        totalNum: '',
        maintenanceCode: '',
        fileList: []
      },
      rules: {
        projectId: { required: true, message: '请选择项目名称', trigger: 'change' },
        branchComId: { required: true, message: '请选择所属分公司', trigger: 'change' },
        equipmentInfo: { required: true, message: '请输入机械、设备使用情况（主要机械情况）', trigger: 'blur' },
        attendanceNum: { required: true, message: '请输入出勤人数（各工种各多少人）', trigger: 'blur' },
        constructionInfo: { required: true, message: '请输入当天施工内容实际完成情况及主要工程量', trigger: 'blur' },
        materialInfo: { required: true, message: '请输入使用的主要材料规格、数量（日消耗量）', trigger: 'blur' },
        meetingInfo: { required: true, message: '请输入施工现场有关会议内容（主要简要概述）', trigger: 'blur' },
        makeInfo: { required: true, message: '请输入试块制作情况', trigger: 'blur' },
        resultInfo: { required: true, message: '请输入材料进场、送检情况及当日取回试验报告编号及结果', trigger: 'blur' },
        totalNum: { required: true, message: '请输入总人数', trigger: 'blur' },
        maintenanceCode: { required: true, message: '请选择维保单编号', trigger: 'blur' }
      },
      mode: this.$route.query.pageTyp === 'add' ? 'add' : 'edit',
      file: {
        mode: this.$route.query.pageTyp === 'add' ? 'add' : 'edit',
        businessCode: 'CUSTOMER01',
        needPage: false,
        fileList: [],
        useMultiDelete: true,
        useMultiExport: true
      },
      tsUserOptions: [],
      planAddFile: planAddFile(),
      planFileList: planFileList(),
      planFileListDel: planFileListDel(),
      getProgrammeArr: [],
      bimData: [],
      proData: [],
      subcontractingData: [],
      treeLoading: false,
      typeData: [],
      projectData: [],
      ownerData: [],
      Options: []
    }
  },
  components: {
    SelectSubCompany,
    SelectProject
  },
  watch: {
    formData: {
      deep: true,
      immediate: true,
      handler(val) {
        this.$checkRequireItem()
      }
    },

    isAudit: {
      // 是否作为审批详情
      immediate: true,
      handler(val) {
        if (val) {
          this.state = 3
        }
      }
    }
  },
  mounted: function () {
    this.initCode()
    this.id = this.$route.query.id
    if (this.state != 1) {
      this.getDetail()
      this.isSubmit = true
    }
  },
  methods: {
    initCode() {
      getMaintenanceInfo().then((res) => {
        const data = []
        res.data.map((node) => {
          data.push({
            label: node.name,
            value: node.code
          })
        })
        this.searchArr[1].data = data
      })
    },
    closeInfo() {
      this.infoQueryParam = {
        status: 1
      }
      this.selectRow = []
      this.tableLoading = false
      this.infoShow = false
    },
    getPlanId() {
      this.modelLoad = true
      if (this.selectRow) {
        this.formData.maintenanceCode = this.selectRow.code
        this.formData.planCode = this.selectRow.planCode
        // this.formData.projectId = this.selectRow.projectId
        this.modelLoad = false
        this.infoShow = false
        this.$refs.RuleForm?.validateField('maintenanceCode')
      } else {
        this.modelLoad = false
        this.infoShow = false
      }
    },
    search(val) {
      this.infoQueryParam = { ...this.infoQueryParam, ...val }
      // this.loadData({ pageSize: 10, pageNo: 1 })
      this.$refs.modalTable.refresh(true)
    },
    getInfo() {
      if (!this.formData.projectId) {
        this.$message.error('请选择项目')
        return false
      } else {
        this.infoShow = true
      }
    },
    loadData(parameter) {
      this.tableLoading = true
      const data = { ...this.infoQueryParam, projectId: this.formData.projectId }
      const searchData = {
        pageSize: parameter.pageSize,
        pageNum: parameter.pageNo,
        param: data
      }
      return getComplaintList(searchData).then((res) => {
        console.log(res)
        if (res.code == 200) {
          this.tableLoading = false
          return { code: 200, data: res.data?.list, total: res.data?.total }
        }
      })
    },
    getDetail() {
      this.loading = true
      getCustomerMaintenanceLogById({ id: this.id }).then((res) => {
        this.formData = res.data
        this.loading = false
      })
    },
    // getBranchComId(value) {
    //   const data = this.$refs.selectSubCompany.getValueName(value)
    //   if (data) {
    //     this.formData.branchComName = data
    //   }
    // },
    // getProId(value) {
    //   this.loading = true
    //   const projectName = this.$refs.selectProject.getValueName(value)
    //   if (projectName) {
    //     this.formData.projectName = projectName
    //   }
    //   getProjectInfo(value).then((res) => {
    //     this.formData.projectManagerId = res.data.projectManagerId
    //     this.formData.projectManager = res.data.projectManagerName
    //     this.formData.planCode = ''
    //     this.formData.maintenanceCode = ''

    //     this.loading = false
    //   })
    // },
    /**
     * @description: 设置分公司和项目信息
     * @param {object} val 选中数据
     * @return {void}
     */
    setProject(val) {
      if (val && val.length > 0) {
        this.formData.branchComId = val[0]?.orgId
        this.formData.branchComName = val[0]?.orgName
        this.formData.projectName = val[1]?.projectName
        const value = val[1]?.projectId
        getProjectInfo(value).then((res) => {
          this.formData.projectManagerId = res.data.projectManagerId
          this.formData.projectManager = res.data.projectManagerName
          this.formData.planCode = this.formData.planCode || ''
          this.formData.maintenanceCode = this.formData.maintenanceCode || ''

          this.loading = false
        })
      }
    },
    // 编辑新增时候的保存
    onSave() {
      this.loading = true
      if (this.state == 1) {
        if (this.formData.totalNum) {
          this.formData.totalNum = this.formData.totalNum.toString()
        }
        insertSelective(this.formData)
          .then((res) => {
            if (res.code == 200) {
              this.loading = false
              this.$message.success('保存成功')
              this.$multiTab.close(this.$route.fullpath)
            }
          })
          .catch((err) => {
            this.loading = false
          })
      } else if (this.state == 2) {
        if (this.formData.totalNum) {
          this.formData.totalNum = this.formData.totalNum.toString()
        }
        updateByPrimaryKeySelective(this.formData)
          .then((res) => {
            if (res.code == 200) {
              this.loading = false
              this.$message.success('保存成功')
              this.$multiTab.close(this.$route.fullpath)
            }
          })
          .catch((err) => {
            this.loading = false
          })
      }
    },
    submit() {
      this.$refs.RuleForm.validate((valid) => {
        if (valid) {
          this.$submitConfirm(async () => {
            this.loading = true
            if (this.formData.totalNum) {
              this.formData.totalNum = this.formData.totalNum.toString()
            }
            submitMaintenanceLog(this.formData).then((res) => {
              if (res.data.code == 200) {
                this.loading = false
                this.$message.success('提交成功')
                this.$multiTab.close(this.$route.fullpath)
              } else {
                this.loading = false
              }
            })
          })
        } else {
          this.$message.warning("请填写完所有必填项信息")
        }
      })
    }
  }
}
</script>
<style scoped lang="less" >
/deep/.ant-modal {
  width: 900px !important;
}
</style>
